package com.cn.jinl.service;

import com.cn.jinl.api.IHealthCheckService;
import com.cn.jinl.api.IPersonnelManageService;
import com.cn.jinl.dao.PersonnelManagementMapper;
import com.cn.jinl.domain.PersonnelManagement;
import com.cn.jinl.domain.PersonnelManagementExample;
import com.cn.jinl.utils.*;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created On : 2023/12/12.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: PersonnelManageServiceImpl
 */
@Service
public class PersonnelManageServiceImpl implements IPersonnelManageService {

    @Autowired
    private PersonnelManagementMapper personnelManagementMapper;

    @Autowired
    private GenerateUUID generateUUID;


    @Autowired
    private IHealthCheckService healthCheckService;



    //人事办理  仅显示3个月内的在职
    @Override
    public List<PersonnelManagement> getCurrentPersonnelList(QueryForm queryForm) throws Exception {
        List<PersonnelManagement> list = personnelManagementMapper.getCurrentPersonnelList(queryForm);
        // 工龄
        this.generateJobyear(list);

        return list;
    }

    //查询统计
    @Override
    public List<PersonnelManagement> getAllPersonnelList(QueryForm queryForm) throws Exception {

        List<PersonnelManagement> list = personnelManagementMapper.getAllPersonnelList(queryForm);
        // 生成 工龄
        this.generateJobyear(list);
        return list;
    }


    @Override
    public String deletePersonnelManagement(QueryForm queryForm) throws Exception {

        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)){
            return "deleteMaterial ids is null";
        }

        PersonnelManagement personnelManagement = new PersonnelManagement();
        personnelManagement.setStatus(Constants.DEL_STATUS);
        PersonnelManagementExample example = new PersonnelManagementExample();
        example.createCriteria().andIdIn(ids);
        int count = personnelManagementMapper.updateByExampleSelective(personnelManagement,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public List<PersonnelManagement> getPersonnelIdAndName() throws Exception {

        List<PersonnelManagement> list = personnelManagementMapper.selectIdAndName();
        return list;
    }

    @Override
    public Map<String, Integer> countPersonnelAndHealth() throws Exception {

        Map<String,Integer> map = Maps.newHashMap();

        //本年新进人员
        int yearNewPersonnel = personnelManagementMapper.countYearNewPersonnel();
        map.put("yearNewPersonnel",yearNewPersonnel);

        //本月新进人员
        int monthNewPersonnel = personnelManagementMapper.countMonthNewPersonnel();
        map.put("monthNewPersonnel",monthNewPersonnel);

        //检疫临期
        int healthNear = healthCheckService.countHealthCheckNear();
        map.put("healthNear",healthNear);

        return map;
    }

    @Override
    public int countZaiZhi() throws Exception {

        int zaizhi = personnelManagementMapper.countZaiZhi();
        return zaizhi;
    }

    @Override
    public int currentYearNumber() throws Exception {

        int yearNumber = personnelManagementMapper.countYearNewPersonnel();
        return yearNumber;
    }

    @Override
    public int currentMonthNumber() throws Exception {
        int monthNumber = personnelManagementMapper.countMonthNewPersonnel();
        return monthNumber;
    }


    @Override
    public String addPersonnelManagement(PersonnelManagement personnelManagement) throws Exception {

        if (null == personnelManagement){
            return "请添加员工信息";
        }

        //查看填入的员工信息是否满足必填字段
        String result = this.personRegistLeagal(personnelManagement);
        if (!"".equals(result)){
            return result;
        }

        //通过身份证号 & 在职状态 判断员工信息是否重复注册
        String IdCard = personnelManagement.getIdCard();
        if (this.countIdCardAndStatus(IdCard,"") > 0){
            return "该员工信息已存在系统中!";
        }

        //生成员工 id
        String personnelManagementId = CommonUtil.generateRandomNum("worker_");
        personnelManagement.setId(personnelManagementId);
        personnelManagement.setStatus(Constants.NORMAL_STATUS);

        //生成员工----工号
        // A or Y +  年(2位) + 当年2位流水 ep:A2210
        String year = personnelManagement.getJoinedDate().substring(2,4);
        String key = personnelManagement.getJobCategory()+"workerNumber"+year;
        int num = generateUUID.getNumberFlag(key);
        String code = "";
        if ("A".equals(personnelManagement.getJobCategory())){
            code = "A" + year + generateUUID.getTwoNumStr(num);
        }else if ("Y".equals(personnelManagement.getJobCategory())){
            code = "Y" + year + generateUUID.getTwoNumStr(num);
        }else {
            return "请选择规定的岗位类别";
        }
        personnelManagement.setJobNumber(code);

        int count = personnelManagementMapper.insertSelective(personnelManagement);

        if (count > 0){
            String result1 = healthCheckService.addHealthCheck(personnelManagementId);
            if (StringUtils.isNotEmpty(result1)){
                throw new Exception("插入健康检定表异常");
            }
        }

        return CommonUtil.outStr(count);
    }


    @Override
    public String updatePersonnelManagement(PersonnelManagement personnelManagement) throws Exception {

        String id = personnelManagement.getId();

        if (StringUtils.isEmpty(id)){
            return "id is null";
        }

        String result = this.personRegistLeagal(personnelManagement);
        if (!"".equals(result)){
            return result;
        }

        //通过身份证号和在职状态看修改信息是否有误
        if (this.countIdCardAndStatus(personnelManagement.getIdCard(),id) > 0){
            return "员工信息重复!";
        }

        PersonnelManagementExample example = new PersonnelManagementExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);

        int count = personnelManagementMapper.updateByExampleSelective(personnelManagement,example);

        return CommonUtil.outStr(count);
    }

    private int countIdCardAndStatus(String idCard,String id) {
        PersonnelManagementExample example = new PersonnelManagementExample();
        PersonnelManagementExample.Criteria criteria = example.createCriteria();

        criteria.andStatusEqualTo(Constants.NORMAL_STATUS).andIdCardEqualTo(idCard).andOnboardingStatusIn(Constants.ONBARDINGSTATUS_WORKING);
        if (StringUtils.isNotEmpty(id)){
            criteria.andIdNotEqualTo(id);
        }

        int count = personnelManagementMapper.countByExample(example);
        return count;

    }

    private String personRegistLeagal(PersonnelManagement personnelManagement){

        String result = "";

        if (StringUtils.isBlank(personnelManagement.getJobCategory())){
            result = "请选择岗位类别";
            return result;
        }else if (!("A".equals(personnelManagement.getJobCategory()) || "Y".equals(personnelManagement.getJobCategory()))){
            result = "请选择正确岗位";
        }

        if (StringUtils.isBlank(personnelManagement.getDeptId())){
            result = "请选择部门";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getEmployeeName())){
            result = "请填写姓名";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getGender())){
            result = "请选择性别";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getBirthday())){
            result = "请输入出生年月";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getIdCard())){
            result = "请填写身份证号";
            return result;
        }else{
            String regex = "\\d{17}[\\d|x|X]";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(personnelManagement.getIdCard());
            boolean isMatched = matcher.matches();
            if (!isMatched){
                result = "请填写正确的身份证号";
                return result;
            }
        }

        if (StringUtils.isBlank(personnelManagement.getHealthStatus())){
            result = "请选择健康检定";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getOnboardingStatus())){
            result = "请选择入职状态";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getJoinedDate())){
            result = "请输入入职日期";
            return result;
        }

        if (StringUtils.isBlank(personnelManagement.getWhetherProbation())){
            result = "请选择是否试用";
            return result;
        }

        return result;
    }

    private void generateJobyear(List<PersonnelManagement> list) throws Exception{
        long timestamp = new Date().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (PersonnelManagement p:list){
            String joinedDate = p.getJoinedDate();
            Date time =simpleDateFormat.parse(joinedDate);
            double stamp = (timestamp - time.getTime())/(1000.0*24.0*3600.0*365.0);
            String jobyear = NumberUtil.getPoint(stamp,1);
            if(StringUtils.equals("0.0",jobyear)){
                jobyear = "0.1";
            }
            p.setJobyear(jobyear);
        }
    }


}
